﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Xml.Linq;

using System.IO;
using System.IO.Compression;
using System.Text;

namespace WebServiceSmart.Router
{
    public class ZipCodec
    {
        private static byte[] EtractBytesFormStream(MemoryStream Ms, int dataBlock)
        {
            byte[] data = null;
            int totalBytesRead = 0;
            GZipStream zipStream = null;
            zipStream = new GZipStream(Ms, CompressionMode.Decompress);
            while (true)
            {
                Array.Resize(ref data, totalBytesRead + dataBlock + 1);
                int bytesRead = zipStream.Read(data, totalBytesRead, dataBlock);
                if (bytesRead == 0)
                {
                    break;
                }
                totalBytesRead += bytesRead;
            }
            Array.Resize(ref data, totalBytesRead);
            return data;
        }


        /// <summary>
        /// Zip压缩算法
        /// </summary>
        /// <param name="data">需压缩的字节数组</param>
        /// <returns>返回压缩后的字节数组</returns>
        /// 
        public static byte[] Compress(byte[] data)
        {
            MemoryStream ms = new MemoryStream();
            GZipStream zipStream = null;
            zipStream = new GZipStream(ms, CompressionMode.Compress, true);
            zipStream.Write(data, 0, data.Length);
            zipStream.Close();
            ms.Position = 0;
            byte[] compressed_data = new byte[ms.Length];
            ms.Read(compressed_data, 0, int.Parse(ms.Length.ToString()));
            ms.Dispose();

            return compressed_data;
        }

        /// <summary>
        /// Zip解压缩算法
        /// </summary>
        /// <param name="data">需解压缩的字节数组</param>
        /// <returns>返回解压缩后的字节数组</returns>
        /// 
        public static byte[] DeCompress(byte[] data)
        {
            MemoryStream ms = new MemoryStream(data);
            byte[] ret = EtractBytesFormStream(ms, data.Length);
            ms.Dispose();
            return ret;
        }
    }
}
